package com.ruoyi.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.pay.entity.WxpayQueryRequest;
import com.ruoyi.pay.entity.WxpayRequest;
import com.ruoyi.pay.utils.Constants;
import com.ruoyi.pay.utils.QRCodeUtil;
import com.ruoyi.pay.utils.WxPayUtils;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/wxpay")
@CrossOrigin
public class WxpayController {

    @Autowired
    private WxPayUtils wxPayUtils;

    @GetMapping("/pay/{orderId}")
    public void pay(@PathVariable("orderId") String orderId, HttpServletResponse response, HttpServletRequest request) throws IOException, DocumentException {
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        //根据官方文档封装请求 XML 报文
        WxpayRequest wxpayRequest = new WxpayRequest();
        wxpayRequest.setAppid(Constants.APP_ID);
        wxpayRequest.setMch_id(Constants.MCH_ID);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        wxpayRequest.setNonce_str(uuid);
        wxpayRequest.setBody("拼夕夕商城订单");
        wxpayRequest.setOut_trade_no(orderId);
        wxpayRequest.setTotal_fee(1);
        String ip = request.getRemoteAddr();
        wxpayRequest.setSpbill_create_ip(ip);
        wxpayRequest.setNotify_url("http://pay.s7.tunnelfrp.com/wxpay/result");
        wxpayRequest.setTrade_type("NATIVE");


        //生成签名
        String json = JSONObject.toJSONString(wxpayRequest);
        Map<String,Object> map = JSONObject.parseObject(json, Map.class);
        Set<String> set = map.keySet();
        List<String> list = new ArrayList(set);
        Collections.sort(list);

        String tempStr = "";
        for (String key : list) {
            tempStr += key + "=" + map.get(key) + "&";
        }
        // key1=value&key2=value&...&keyN=valueN&   key=密钥
        tempStr += "key="+Constants.API_KEY;

        String sign = DigestUtils.md5Hex(tempStr).toUpperCase();
        wxpayRequest.setSign(sign);


        XStream xStream = new XStream();
        xStream.alias("xml", WxpayRequest.class);
        String requestXML = xStream.toXML(wxpayRequest).replaceAll("__","_");
        System.out.println("请求报文：");
        System.out.println(requestXML);

        // 借助 HttpClient 发送报文并接收返回的 XML 报文
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        HttpEntity requestEntity = new StringEntity(requestXML,"UTF-8");
        post.setEntity(requestEntity);
        HttpResponse httpResponse = httpClient.execute(post);
        HttpEntity responseEntity = httpResponse.getEntity();
        String responseXML = EntityUtils.toString(responseEntity, "UTF-8");
        System.out.println("响应报文：");
        System.out.println(responseXML);

        //从返回的XML 报文中，解析出 codeURL
        // 解析 XML 工具 ： dom4j  jdom

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new ByteArrayInputStream(responseXML.getBytes("UTF-8")));
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();

        String codeUrl = null;
        for (Element element : elements) {
            if(element.getName().equals("code_url")){
                codeUrl =  element.getStringValue();
            }
        }



        //将二维码的字符串转成图片，返回给浏览器
        QRCodeUtil.createQRCode(response,codeUrl);
    }

    @RequestMapping("/result")
    public void result(){
        System.out.println("收到微信支付结果。。。");

    }

    @GetMapping("/query/{orderId}")
    public Boolean pay(@PathVariable("orderId") String orderId) throws Exception {

        String url = "https://api.mch.weixin.qq.com/pay/orderquery";

        //根据官方文档封装请求 XML 报文
        WxpayQueryRequest wxpayQueryRequest = new WxpayQueryRequest();
        wxpayQueryRequest.setAppid(Constants.APP_ID);
        wxpayQueryRequest.setMch_id(Constants.MCH_ID);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        wxpayQueryRequest.setNonce_str(uuid);
        wxpayQueryRequest.setOut_trade_no(orderId);


        //生成签名
        String json = JSONObject.toJSONString(wxpayQueryRequest);
        Map<String,Object> map = JSONObject.parseObject(json, Map.class);
        Set<String> set = map.keySet();
        List<String> list = new ArrayList(set);
        Collections.sort(list);

        String tempStr = "";
        for (String key : list) {
            tempStr += key + "=" + map.get(key) + "&";
        }
        // key1=value&key2=value&...&keyN=valueN&   key=密钥
        tempStr += "key="+Constants.API_KEY;

        String sign = DigestUtils.md5Hex(tempStr).toUpperCase();
        wxpayQueryRequest.setSign(sign);


        XStream xStream = new XStream();
        xStream.alias("xml", WxpayQueryRequest.class);
        String requestXML = xStream.toXML(wxpayQueryRequest).replaceAll("__","_");
        System.out.println("请求报文：");
        System.out.println(requestXML);

        // 借助 HttpClient 发送报文并接收返回的 XML 报文
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        HttpEntity requestEntity = new StringEntity(requestXML,"UTF-8");
        post.setEntity(requestEntity);
        HttpResponse httpResponse = httpClient.execute(post);
        HttpEntity responseEntity = httpResponse.getEntity();
        String responseXML = EntityUtils.toString(responseEntity, "UTF-8");
        System.out.println("响应报文：");
        System.out.println(responseXML);

        //从返回的XML 报文中，解析出 codeURL
        // 解析 XML 工具 ： dom4j  jdom

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new ByteArrayInputStream(responseXML.getBytes("UTF-8")));
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();

//        String codeUrl = null;
//        for (Element element : elements) {
//            if(element.getName().equals("code_url")){
//                codeUrl =  element.getStringValue();
//            }
//        }

        return false;
    }
}
